package com.qing.demo.netty.server;

import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.SocketChannel;

import java.nio.charset.Charset;


/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class MyServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String msg=packet.content().toString(Charset.forName("utf-8"));
        System.out.println("UDP服务端接收到数据："+msg);

//        向客户端发送消息
        String info="UDP服务端已收到数据\r\n";
//        由于数据报的数据是以字符串数组的形式存储的，所以，需要将发送的数据转换为字节数组
        byte[] bytes=info.getBytes(Charset.forName("utf-8"));
        DatagramPacket datagramPacket = new DatagramPacket(Unpooled.copiedBuffer(bytes),packet.sender());
        ctx.writeAndFlush(datagramPacket);

    }

}
